import { createRouter, createWebHistory } from 'vue-router'
import type { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      component: () => import('../views/login/index.vue')
    },
    {
      path: '/',
      component: () => import('../layouts/AdminLayout.vue'),
      children: [
        {
          path: '',
          component: () => import('../views/dashboard/index.vue')
        },
        {
          path: 'system',
          component: () => import('../views/system/index.vue')
        },
        {
          path: 'system/:systemId/workflows',
          children: [
            {
              path: '',
              component: () => import('../views/system/workflows/index.vue')
            },
            {
              path: 'create',
              component: () => import('../views/system/workflows/editor.vue')
            }
          ]
        }
      ]
    },
    {
      path: '/system/:systemId/workflows/:id/view',
      component: () => import('../views/system/workflows/editor.vue'),
      meta: { title: '查看流程' }
    },
    {
      path: '/system/:systemId/workflows/:id/edit',
      component: () => import('../views/system/workflows/editor.vue'),
      meta: { title: '编辑流程' }
    },
    {
      path: '/system/:systemId/workflows/create',
      component: () => import('../views/system/workflows/editor.vue'),
      meta: { title: '新建流程' }
    }
  ]
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  
  if (to.path === '/login' && isAuthenticated) {
    // 已登录用户访问登录页，重定向到首页
    next('/')
  } else if (to.path !== '/login' && !isAuthenticated) {
    // 未登录用户访问其他页面，重定向到登录页
    next('/login')
  } else {
    // 其他情况正常放行
    next()
  }
})

export default router 